package android_serialport_api.utils;

public class MyFunc {

	public static int isOdd(int num) {
		return num & 1;
	}

	public static int HexToInt(String inHex) {
		return Integer.parseInt(inHex, 16);
	}

	public static byte HexToByte(String inHex) {
		return (byte) Integer.parseInt(inHex, 16);
	}

	public static String Byte2Hex(Byte inByte) {
		return String.format("%02x", inByte).toUpperCase();
	}

	public static String ByteArrToHex(byte[] inBytArr) {
		StringBuilder strBuilder = new StringBuilder();
		int j = inBytArr.length;

		for (int i = 0; i < j; ++i) {
			strBuilder.append(Byte2Hex(inBytArr[i]));
			strBuilder.append(" ");
		}

		return strBuilder.toString();
	}

	public static String ByteArrToHex(byte[] inBytArr, int offset, int byteCount) {
		StringBuilder strBuilder = new StringBuilder();
		int j = byteCount;

		for (int i = offset; i < j; ++i) {
			strBuilder.append(Byte2Hex(inBytArr[i]));
		}

		return strBuilder.toString();
	}

	/**
	 * byte[] 转 String
	 *
	 * @param str
	 * @return
	 */
	public static byte[] strToByteArray(String str) {
		if (str == null) {
			return null;
		}
		byte[] byteArray = str.getBytes();
		return byteArray;
	}

	public static int byteArrayToInt(byte[] b) {
		return b[3] & 0xFF | (b[2] & 0xFF) << 8 | (b[1] & 0xFF) << 16 | (b[0] & 0xFF) << 24;
	}

	public static byte[] intToByteArray(int a) {
		return new byte[] { (byte) ((a >> 24) & 0xFF), (byte) ((a >> 16) & 0xFF), (byte) ((a >> 8) & 0xFF),
				(byte) (a & 0xFF) };
	}

	/**
	 * 将16位byte[] 转换为32位的HEX格式的字符串String
	 *
	 * @param src
	 * @return
	 */
	public static String Bytes2Hex(byte[] src) {
		StringBuilder builder = new StringBuilder();
		if (src == null || src.length <= 0) {
			return null;
		}
		char[] buffer = new char[2];
		for (int i = 0; i < src.length; i++) {
			buffer[0] = Character.forDigit((src[i] >>> 4) & 0x0F, 16);
			buffer[1] = Character.forDigit(src[i] & 0x0F, 16);
			builder.append(buffer);
		}
		return builder.toString();
	}

	public static byte[] HexToByteArr(String inHex) {
		int hexlen = inHex.length();
		byte[] result;
		if (isOdd(hexlen) == 1) {
			++hexlen;
			result = new byte[hexlen / 2];
			inHex = "0" + inHex;
		} else {
			result = new byte[hexlen / 2];
		}

		int j = 0;

		for (int i = 0; i < hexlen; i += 2) {
			result[j] = HexToByte(inHex.substring(i, i + 2));
			++j;
		}

		return result;
	}
}